'use client'

import { zodResolver } from '@hookform/resolvers/zod'
import { Button, CircularProgress } from '@mui/material'
import Box from '@mui/material/Box'
import { useMutation } from '@tanstack/react-query'
import { AxiosError } from 'axios'
import { useRouter } from 'next/navigation'
import { type SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'

import { TextFieldControlled } from '@/components/forms/TextFieldControlled'

import type { IAuthForm } from '@/types/auth.types'
import { loginScheme } from '@/types/auth.types'

import { DASHBOARD_PAGES } from '@/config/pages-url.config'

import { authService } from '@/services/auth.service'

export function Login() {
	const {
		control,
		setError,
		formState: { errors, isDirty, isValid },
		handleSubmit,
		reset
	} = useForm<IAuthForm>({
		mode: 'onChange',
		resolver: zodResolver(loginScheme),
		defaultValues: {
			username: '',
			password: ''
		}
	})

	const { push } = useRouter()

	const { mutate, isPending } = useMutation({
		mutationKey: ['auth'],
		mutationFn: (data: IAuthForm) => authService.main(data),
		onSuccess: () => {
			toast.success('Вы успешно авторизовались')
			reset()
			push(DASHBOARD_PAGES.HOME)
		},
		onError: error => {
			if (
				error instanceof AxiosError &&
				error.response?.data?.non_field_errors
			) {
				toast.error(error.response.data.non_field_errors[0])
				setError('username', {
					type: 'server',
					message: ''
				})
				setError('password', {
					type: 'server',
					message: ''
				})
				setError('root', {
					type: 'server',
					message: error.response.data.non_field_errors[0]
				})
			} else if (error.message === 'Network Error')
				toast.error('Сервис недоступен, попробуйте позже')
			else toast.error('Ошибка авторизации')
		}
	})

	const onSubmit: SubmitHandler<IAuthForm> = data => {
		mutate(data)
	}

	return (
		<div className='flex flex-col gap-5 min-h-screen w-full justify-center items-center'>
			<h1 className='text-3xl font-bold'>Вход в систему</h1>
			<form
				onSubmit={handleSubmit(onSubmit)}
				className='flex flex-col gap-4'
				noValidate
			>
				<TextFieldControlled
					control={control}
					name='username'
					label='Логин'
					disabled={isPending}
				/>
				<TextFieldControlled
					control={control}
					name='password'
					label='Пароль'
					type='password'
					disabled={isPending}
				/>
				{errors?.root && <p className='text-red-500'>{errors.root.message}</p>}
				<Box
					sx={{
						display: 'flex'
					}}
				>
					<Button
						type='submit'
						variant='contained'
						disabled={isPending || !isDirty || !isValid}
					>
						Войти
					</Button>
					{isPending && (
						<CircularProgress
							sx={{
								ml: 2
							}}
						/>
					)}
				</Box>
			</form>
		</div>
	)
}
